package com.finna.tenant.service.impl;

import com.finna.tenant.dto.*;
import com.finna.tenant.dto.AccountDTO.AccountCreateRequest;
import com.finna.tenant.dto.AccountDTO.AccountListRequest;
import com.finna.tenant.dto.AccountDTO.AccountResponse;
import com.finna.tenant.dto.AccountDTO.AccountUpdateRequest;
import com.finna.tenant.dto.TenantAccountJoinDTO.TenantAccountJoinCreateRequest;
import com.finna.tenant.entity.Account;
import com.finna.tenant.entity.Tenant;
import com.finna.tenant.mapper.AccountMapper;
import com.finna.tenant.mapper.TenantMapper;
import com.finna.tenant.service.AccountService;
import com.finna.tenant.service.TenantAccountJoinService;
import com.finna.tenant.utils.EncryptionUtils;
import com.finna.tenant.utils.PasswordUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 账号Service实现
 */
@Service
public class AccountServiceImpl implements AccountService {
    
    private static final Logger logger = LoggerFactory.getLogger(AccountServiceImpl.class);
    
    @Autowired
    private AccountMapper accountMapper;
    
    @Autowired
    private TenantMapper tenantMapper;
    
    @Autowired
    private TenantAccountJoinService tenantAccountJoinService;
    
    @Autowired
    private PasswordUtils passwordUtils;
    
    @Autowired
    private EncryptionUtils encryptionUtils;
    
    @Value("${app.encryption.key:default-secret-key-16byte}")
    private String encryptionKey;
    
    private final ObjectMapper objectMapper = new ObjectMapper();
    
    @Override
    @Transactional
    public AccountResponse create(AccountCreateRequest request) {
        // 检查邮箱是否已存在
        Account existingAccount = accountMapper.selectByEmail(request.getEmail());
        if (existingAccount != null) {
            throw new RuntimeException("邮箱已被使用");
        }
        
        // 检查用户名重复
        int userCount = accountMapper.countByUsername(request.getName());
        String username = request.getName();
        if (userCount > 0) {
            username = username + "_" + (userCount + 1);
        }
        
        // 创建账号
        Account account = new Account();
        //TODO 生成账号
        account.setAccount(123456L);
        account.setName(username);
        account.setEmail(request.getEmail());
        
        // 处理密码
        if (request.getPassword() != null && !request.getPassword().isEmpty()) {
            String salt = passwordUtils.generateSalt();
            String hashedPassword = passwordUtils.hashPassword(request.getPassword(), salt);
            account.setPassword(hashedPassword);
            account.setPasswordSalt(salt);
        }
        
        account.setInterfaceTheme(request.getInterfaceTheme() != null ? request.getInterfaceTheme() : "light");
        account.setInterfaceLanguage(request.getInterfaceLanguage() != null ? request.getInterfaceLanguage() : "zh-Hans");
        account.setTimezone(request.getTimezone() != null ? request.getTimezone() : "Asia/Shanghai");
        account.setStatus("active");
        account.setInitializedAt(LocalDateTime.now());
        account.setIsAdmin(false);
        account.setCreateTime(LocalDateTime.now());
        account.setUpdateTime(LocalDateTime.now());
        account.setDeleted(false);
        
        accountMapper.insert(account);
        logger.info("创建账号成功: id={}, email={}", account.getId(), account.getEmail());
        
        // 初始化租户
//        initializeTenant(account);
        
        return convertToResponse(account);
    }
    
    /**
     * 初始化租户
     */
    private void initializeTenant(Account account) {
        // 创建默认租户
        Tenant tenant = new Tenant();
        tenant.setTenantName(account.getName() + "'s Workspace");
        tenant.setTenantCode(UUID.randomUUID().toString());
        tenant.setStatus(1);
        tenant.setIsAdmin(false);
        tenant.setIsPublic(false);
        tenant.setCreateTime(LocalDateTime.now());
        tenant.setUpdateTime(LocalDateTime.now());
        tenant.setCreateBy(account.getId());
        tenant.setUpdateBy(account.getId());
        tenant.setDeleted(false);
        
        tenantMapper.insert(tenant);
        
        // 创建租户账号关联
        TenantAccountJoinCreateRequest tenantAccountJoinCreateRequest = TenantAccountJoinCreateRequest.builder()
                .tenantId(tenant.getId())
                .accountId(account.getId())
                .role("owner")
                .build();
        tenantAccountJoinService.create(tenantAccountJoinCreateRequest);
        
        logger.info("账号初始化租户成功: accountId={}, tenantId={}", account.getId(), tenant.getId());
    }
    
    @Override
    @Transactional
    public AccountResponse update(Long id, AccountUpdateRequest request) {
        Account account = accountMapper.selectById(id);
        if (account == null) {
            throw new RuntimeException("账号不存在");
        }
        
        if (request.getName() != null) {
            account.setName(request.getName());
        }
        if (request.getEmail() != null) {
            account.setEmail(request.getEmail());
        }
        if (request.getPassword() != null && !request.getPassword().isEmpty()) {
            String salt = passwordUtils.generateSalt();
            String hashedPassword = passwordUtils.hashPassword(request.getPassword(), salt);
            account.setPassword(hashedPassword);
            account.setPasswordSalt(salt);
        }
        if (request.getInterfaceTheme() != null) {
            account.setInterfaceTheme(request.getInterfaceTheme());
        }
        if (request.getInterfaceLanguage() != null) {
            account.setInterfaceLanguage(request.getInterfaceLanguage());
        }
        if (request.getTimezone() != null) {
            account.setTimezone(request.getTimezone());
        }
        if (request.getStatus() != null) {
            account.setStatus(request.getStatus());
        }
        account.setUpdateTime(LocalDateTime.now());
        
        accountMapper.updateById(account);
        logger.info("修改账号成功: id={}", id);
        
        return convertToResponse(account);
    }
    
    @Override
    @Transactional
    public void delete(Long id) {
        Account account = accountMapper.selectById(id);
        if (account == null) {
            throw new RuntimeException("账号不存在");
        }
        
        // 软删除账号
        accountMapper.deleteById(id);
        
        logger.info("删除账号成功: id={}", id);
    }
    
    @Override
    public AccountResponse getById(Long id) {
        Account account = accountMapper.selectById(id);
        if (account == null) {
            throw new RuntimeException("账号不存在");
        }
        return convertToResponse(account);
    }
    
    @Override
    public PageResponse<AccountResponse> list(AccountListRequest request) {
        // 构建查询参数
        Map<String, Object> params = new HashMap<>();
        if (request.getName() != null && !request.getName().isEmpty()) {
            params.put("name", request.getName());
        }
        if (request.getEmail() != null && !request.getEmail().isEmpty()) {
            params.put("email", request.getEmail());
        }
        if (request.getStatus() != null) {
            params.put("status", request.getStatus());
        }
        
        // 分页参数
        Integer page = request.getPage() != null ? request.getPage() : 1;
        Integer pageSize = request.getPageSize() != null ? request.getPageSize() : 10;
        if (pageSize > 100) {
            pageSize = 100;
        }
        
        // 使用PageHelper进行分页
        PageHelper.startPage(page, pageSize);
        List<Account> accounts = accountMapper.selectList(params);
        PageInfo<Account> pageInfo = new PageInfo<>(accounts);
        
        // 转换为响应对象
        List<AccountResponse> responses = pageInfo.getList().stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
        
        return new PageResponse<>(responses, pageInfo.getTotal(), page, pageSize);
    }
    
    /**
     * 转换为响应对象
     */
    private AccountResponse convertToResponse(Account account) {
        AccountResponse response = new AccountResponse();
        response.setId(account.getId());
        response.setAccount(account.getAccount());
        response.setName(account.getName());
        response.setEmail(account.getEmail());
        response.setAvatar(account.getAvatar());
        response.setInterfaceLanguage(account.getInterfaceLanguage());
        response.setInterfaceTheme(account.getInterfaceTheme());
        response.setTimezone(account.getTimezone());
        response.setLastLoginAt(account.getLastLoginAt());
        response.setLastLoginIp(account.getLastLoginIp());
        response.setLastActiveAt(account.getLastActiveAt());
        response.setStatus(account.getStatus());
        response.setInitializedAt(account.getInitializedAt());
        response.setIsAdmin(account.getIsAdmin());
        response.setIsSuperAdmin(account.getIsSuperAdmin());
        response.setCreatedAt(account.getCreateTime());
        response.setUpdatedAt(account.getUpdateTime());
        return response;
    }
}

